package com.example.arithmeticleetcode.leetcode.September;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-09-25 11:30
 **/
public class Demo20 {

    public static void main(String[] args) {
        System.out.println(bitwiseComplement(5));
        System.out.println(bitwiseComplement(7));
        System.out.println(bitwiseComplement(10));
        System.out.println(bitwiseComplement2(5));
        System.out.println(bitwiseComplement2(7));
        System.out.println(bitwiseComplement2(10));
    }

    public static int bitwiseComplement(int N) {
        if (N == 0) {
            return 1;
        }
        StringBuilder stringBuilder = new StringBuilder();
        while (N != 0) {
            if (N % 2 == 1) {
                stringBuilder.append(0);
            } else  {
                stringBuilder.append(1);
            }
            N = N / 2;
        }
        String s = stringBuilder.toString();
        int sum = 0;
        for (int i = 0, len = s.length(); i < len; i++) {
            if (s.charAt(i) == '1') {
                sum += Math.pow(2, i);
            }
        }
        return sum;
    }

    public static int bitwiseComplement2(int N) {
        int num = 1;
        while(num < N){
            int temp = num << 1;
            num = temp + 1;
        }
        return N ^ num;
    }
}
